package thread.demo02;

import org.apache.commons.io.FileUtils;
import thread.demo01.TestThread2;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.concurrent.*;

/**
 * @author 真香
 * @create 2021-06-03 12:02
 */


/**
 * callable的好处
 * 1、可以定义返回值
 * 2、可以抛出异常
 *
 */
public class TestCallable  implements Callable<Boolean>{

    // 网络图片地址
    private String url;

    // 保存文件名
    private String name;


    public TestCallable(String url,String name) {
        this.url = url;
        this.name = name;
    }


    /**
     * 下载图片的线程执行体
     */
    @Override
    public Boolean call() {

      WebDownLoader webDownLoader = new WebDownLoader();
        webDownLoader.downloader(url,name);
        System.out.println("下载了文件名为"+name);
        return  true;

    }
    public static void main(String[] args) throws ExecutionException, InterruptedException {

        TestCallable thread1 = new TestCallable("https://pics0.baidu.com/feed/91529822720e0cf30c0b69c1b1506a17be09aa2f.jpeg?token=132622209e1168d74b3cc465666e6116","鸿蒙概念图1.jpg");
        TestCallable thread2 = new TestCallable("https://pics0.baidu.com/feed/91529822720e0cf30c0b69c1b1506a17be09aa2f.jpeg?token=132622209e1168d74b3cc465666e6116","鸿蒙概念图2.jpg");
        TestCallable thread3 = new TestCallable("https://pics0.baidu.com/feed/91529822720e0cf30c0b69c1b1506a17be09aa2f.jpeg?token=132622209e1168d74b3cc465666e6116","鸿蒙概念图3.jpg");

        // 1. 创建执行任务：ExecutorService ser = Executors.newFixedThreadPool(1);
        ExecutorService ser = Executors.newFixedThreadPool(3);
        // 2. 提交执行：
        Future<Boolean> result1 = ser.submit(thread1);
        Future<Boolean> result2 = ser.submit(thread2);
        Future<Boolean> result3 = ser.submit(thread3);

        // 3. 获取结果：
        boolean r1 = result1.get();
        boolean r2 = result2.get();
        boolean r3 = result3.get();

        System.out.println(r1);
        System.out.println(r2);
        System.out.println(r3);

        // 4. 关闭服务：
        ser.shutdownNow();

    }

}





class WebDownLoader {


    /**
     * 下载方法
     *
     * @param url
     * @param name
     */
    public void downloader(String url, String name) {

        try {
            FileUtils.copyURLToFile(new URL(url), new File(name));
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("IO异常，downloader方法出现问题");


        }
    }
}
